﻿using SimplePipeHelper.Server;
using System;
using System.Text;
using System.Threading;

namespace NetFrameworkServer
{
    class PipeServerHelper
    {
        private SimplePipeServer _pipeServer;

        public void StartTest(string pipeName)
        {
            _pipeServer = new SimplePipeServer { PipeName = pipeName };
            _pipeServer.PipeServerStart += OnPipeServerStart;
            _pipeServer.PipeServerClosed += OnPipeServerClosed;
            _pipeServer.PipeClientConnect += OnPipeClientConnect;
            _pipeServer.PipeClientClosed += OnPipeClientClosed;
            _pipeServer.DataReceived += OnDataReceived;
            _pipeServer.Start();
        }

        public void StopTest()
        {
            (_pipeServer as IDisposable)?.Dispose();
            _pipeServer = null;
        }

        private void OnPipeServerStart(bool result)
        {
            Console.WriteLine($"OnPipeServerStart: {result}");

            if (!result)
            {
                Console.WriteLine($"LastErrorMessage: {_pipeServer.LastErrorMessage}");
                _pipeServer.Stop();
            }
        }

        private void OnPipeServerClosed()
        {
            Console.WriteLine("OnPipeServerClosed");
            StopTest();
        }

        private void OnPipeClientConnect()
        {
            Console.WriteLine("OnPipeClientConnect");
        }

        private void OnPipeClientClosed()
        {
            Console.WriteLine("OnPipeClientClosed");
        }

        private void OnDataReceived(byte[] buffer)
        {
            var message = Encoding.UTF8.GetString(buffer);
            Console.WriteLine($"OnDataReceived: {message}");

            Thread.Sleep(100);
            message = "pipe server send message to pipe client";
            var bytes = Encoding.UTF8.GetBytes(message);
            _pipeServer?.SendMessage(bytes);
        }
    }
}
